<?php

namespace App\Http\Services;

use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Requests\CaptchaDTO;
use App\Http\Traits\Errors;
use App\Models\PayMethod;
use Carbon\Carbon;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Illuminate\Support\Facades\Cache;
use Ramsey\Uuid\Uuid;

class PlatformService extends BaseService
{
    use Errors;

    public function captchaCreate()
    {
        $phrase = new PhraseBuilder();
        // 设置验证码位数
        $code = $phrase->build(4);
        // 生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder($code, $phrase);
        // 设置背景颜色25,25,112
        $builder->setBackgroundColor(255, 255, 255);
        // 设置倾斜角度
        $builder->setMaxAngle(2);
        // 设置验证码后面最大行数
        $builder->setMaxBehindLines(0);
        // 设置验证码前面最大行数
        $builder->setMaxFrontLines(0);
        // 设置验证码颜色
        $builder->setTextColor(123, 123, 123);
        // 可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        // 获取验证码的内容
        $phrase = $builder->getPhrase();
        // 把内容存入 cache，10分钟后过期
        $client_id = Uuid::uuid1()->toString();
        Cache::put($client_id, $phrase, Carbon::now()->addMinutes(5));
//        Log::info('client==='.$client_id.'==code='.$phrase);
        // 组装接口数据
        $data = [
            'client'  => $client_id,
            'captcha' => $phrase,
        ];
        return $data;
    }

    public function validateCaptcha(CaptchaDTO $captchaDTO)
    {
        $client = $captchaDTO->input('client') ?? '';
        $code   = $captchaDTO->input('code') ?? '';
        if (strtolower(Cache::get($client)) != strtolower($code)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('图形验证码错误'));
        }
        return true;
    }

    public function payMethodList()
    {
        return PayMethod::where('status',1)->get(['id','slug','icon','name','rate','desc']);
    }

}
